<?php

namespace apiend\models;

use Yii;
use apiend\models\User;
use common\models\user\UserConnect;
use common\models\ThirdPartyAuthorization;

/**
 * 第三方登录授权
 * ThirdPartyAuthForm
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class ThirdPartyAuthForm extends ThirdPartyAuthorization {

    /**
     * Signs user up.
     * @return User|null the saved model or null if saving fails
     */
    public function connect() {
        $auth = $this->authent();
        if ($auth === false && !($auth instanceof UserConnect)) {
            return $this->dumpError('授权获取失败');
        }
        $debug = [];
        $token = $this->token;
        if (!$auth->user_id && $token->user_id) {
            $auth->user_id = $token->user_id;
            if (!$auth->save()) {
                return $this->dumpError('授权绑定用户失败');
            }
            $debug[] = [
                'save $auth->user_id' => $auth->user_id,
            ];
        }
        if ($auth->user_id && $auth->meta && $auth->meta->mobile) {
            if (!$token->bindUser($auth->user_id)) {
                $this->dumpError('授权信息Token绑定失败');
            }
            return $auth->meta;
        }
        return [
            'connect_id' => $auth->id
        ];
    }

}
